﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TranslationService.cs" company="WordSteps.com">
//   All rights reserved
// </copyright>
// <summary>
//   Defines the TranslationService type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace RapidDict.Modules.TranslationService.Services
{
    using System;
    using Google.API.Translate;
    using RapidDict.Infrastructure.Interfaces;

    public class TranslationService : ITranslationService
    {
        public event EventHandler WordChanged;

        private string phrase;
        private readonly ILanguagePairService languagePairService;
        
        public TranslationService(ILanguagePairService languagePairService)
        {
            this.languagePairService = languagePairService;
            this.phrase = string.Empty;

            this.languagePairService.SourceLanguageChanged += (s, e) => this.NotifyWordChanged();
            this.languagePairService.TargetLanguageChanged += (s, e) => this.NotifyWordChanged();
        }

        public string GetWord()
        {
            return this.phrase;
        }

        public void SetWord(string phrase)
        {
            this.phrase = phrase.Trim();
            if (this.WordChanged != null)
            {
                this.WordChanged(this, EventArgs.Empty);
            }
        }

        public void NotifyWordChanged()
        {
            if (this.WordChanged != null)
            {
                this.WordChanged(this, EventArgs.Empty);
            }
        }

        public string GetTranslation()
        {
            if (String.IsNullOrEmpty(this.phrase))
            {
                return String.Empty;
            }
                
            try
            {
                var client = new TranslateClient("http://RapidDict.com");
                
                return client.Translate(this.phrase, this.languagePairService.GetSourceLanguage().Code, this.languagePairService.GetTargetLanguage().Code);
            }
            catch (Exception)
            {
                return String.Empty;
            }
        }
    }
}